import * as API_Goods from '../../../../api/goods'
import * as API_Address from '../../../../api/address'
const app = getApp();
let currentLocation = {};

Component({
  properties: {
    goodsId: String,
    sellerId: Number
  },
  data: {
    region: '',
    hasSelect: [],
    locations: '',
    in_store: 2,
    showSelector: false,
    ship: {},
    shipFee: '',
    shipEndTime: ''
  },
  // 生命周期
  lifetimes: {
    ready() {
      const { defaultLocation, locationData } = app.globalData;
      currentLocation = locationData.hasAuth ? locationData : defaultLocation;
      this.setData({
        region: currentLocation.detailAddress,
        locations: currentLocation.buildingPosition
      });
      this.getShipData();
    }
  },
  methods: {
    //打开地址选择器
    openAddress() {
      this.setData({ showSelector: true })
    },
    popup() {
      this.selectComponent('#bottomFrame').showFrame();
    },
    async closeRegionpicke() {
      this.geoAddress(this.data.region);
      this.selectComponent('#bottomFrame').hideFrame();
    },
    //地址发生改变
    addressSelectorChanged(object) {
      const item = object.detail
      const area_id = item[item.length - 1].id
      const region = item.map(key => { return key.local_name }).join('')
      API_Goods.getGoodsShip(this.data.goodsId, area_id).then(response => {
        this.setData({
          showSelector: false,
          in_store: response,
          region: region,
          hasSelect: item
        })
        this.triggerEvent('in-stock-change', response)
      })
    },
    // 获取物流信息
    async getShipData() {
      const { goodsId, sellerId } = this.properties;
      const locations = this.data.locations.split(',') || {};

      API_Goods.searchShip(goodsId, locations[1], locations[0]).then(ship => {
        const { shop_is_open } = ship;
        this.setData({ ship });
        // this.getShipFee();
      }).catch(err => {
        console.log('ship error ' + JSON.stringify(err));
      });
    },
    // 获取运费
    getShipFee() {
      const { ship = {} } = this.data;

      const {

        // 错误
        error_msg,
        // 全国/本地
        is_local, is_global,
        allow_global_ship, allow_local_ship,
        // 全国配送价格、派送时间、送达时间
        global_ship_price, global_start_time, global_end_time,
        // 本地配送价格、派送时间、送达时间
        local_ship_price, local_start_time, local_end_time } = ship;

      // 无异常
      const isYes = (is_local && allow_local_ship) || (is_global && allow_global_ship);

      // 配送费用
      const l_price = allow_local_ship ? `同城配送${local_ship_price}元` : '';
      const g_price = allow_global_ship ? global_ship_price ? `快递${global_ship_price}元` : '快递免运费' : '';

      const shipFee = isYes ? `${l_price}${allow_local_ship ? '/' : ''}${g_price}` : error_msg;

      // 下单时间
      const g_start_time = allow_global_ship ? `${global_start_time ? global_start_time : ''}` : '';
      const l_start_time = allow_local_ship ? `${local_start_time ? local_start_time : ''}` : '';
      // 送达时间
      const g_end_time = allow_global_ship ? `${global_end_time}送达` : '';
      const l_end_time = allow_local_ship ? `${local_end_time}送达` : '';
      const shipEndTime = isYes ? `${allow_local_ship ? l_start_time : g_start_time} 预计${allow_local_ship ? l_end_time : g_end_time}` : '';
      this.setData({
        isYes,
        shipFee,
        shipEndTime,
      });
    },

    // 获取地址信息
    geoAddress(address) {
      API_Address.geoAddress(address).then((data = {}) => {
        if (data && data.geocodes) {
          const geocodes = data.geocodes;
          const { formatted_address = '', province, city, district, location } = geocodes[0];

          const currentPosition = {
            // 省
            province,
            // 市,直辖市返回空
            city,
            // 区
            district,
            // 详细位置
            detailAddress: formatted_address,
            //经度，纬度
            location,
          };

          this.currentPosition = currentPosition;

          this.getShipData();
          // this.setState({backEle: addressComponent.province || ''});
        }
      }).catch(err => {
        console.log(`?? location err ${JSON.stringify(err)}`);
      });
    }
  }
})